# -*- coding: UTF-8 -*- 
__author__ = 'xiang'

import pymongo
from scrapy.exceptions import DropItem
import re
import time

class MongoPipeline(object):
    def __init__(self, mongo_url, mongo_db,mongo_conlection):
        self.mongo_url = mongo_url
        self.mongo_db = mongo_db
        self.mongo_conlection = mongo_conlection

    @classmethod
    def from_crawler(cls, crawler):
        print(crawler.settings.get('mongo_url'))
        return cls(
            mongo_url=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DB'),
            mongo_conlection =crawler.settings.get('MONGO_CONNECTION'),
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_url)
        self.db = self.client[self.mongo_db]
        self.collection = self.db[self.mongo_conlection]
        self.collection.create_index('job_insert_timestamp', unique=True)

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        try :
            price = item["job_price"]
            if re.match(r'\d+-\d+',price)  is not None:
                prices = price.split('-')
                price = (int(prices[0]) + int(prices[1])) / 2
                item['job_price'] = price
            time.sleep(0.1)
            self.collection.insert_one(dict(item))
            return  item
        except Exception as e:
            spider.logger.debug(' duplicate key error collection %s'%(e))
            return item







